package com.yantong.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.yantong.constant.OrderStatus;
import com.yantong.constant.PayType;
import com.yantong.constant.RefundStatus;
import com.yantong.utils.PageUtils;
import com.yantong.service.CommissionService;
import com.yantong.pojo.PayChannel;
import com.yantong.service.PayChannelService;
import com.yantong.pojo.Order;
import com.yantong.pojo.OrderProduct;
import com.yantong.pojo.OrderProductExample;
import com.yantong.pojo.OrderRefund;
import com.yantong.mapper.OrderMapper;
import com.yantong.mapper.OrderProductMapper;
import com.yantong.mapper.OrderRefundMapper;
import com.yantong.service.PayService;
import com.yantong.service.RefundService;
import com.yantong.service.MemberIntegralService;
import com.yantong.enums.PayChannelEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kanghaixin
 * @date 2018/9/10.17:45
 */
@Service
public class RefundServiceImpl implements RefundService {
    @Autowired
    private OrderRefundMapper orderRefundMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;
//    @Autowired
//    @Lazy
//    private PayService payService;
//    @Autowired
//    private PayChannelService payChannelService;
//    @Autowired
//    private MemberIntegralService integralService;
//    @Autowired
//    private CommissionService commissionService;

    @Override
    public PageUtils<OrderRefund> listOrderRefund(Date start, Date end, Long centreId, Long teamId, String queryItem, Integer status, int offset, int limit) {
        Map<String, Object> params = new HashMap<>(4);
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (status != null) {
            params.put("status", status);
        }

        PageUtils<OrderRefund> pageUtils = new PageUtils<>();
        int total = orderRefundMapper.countByParams(params);
        if (total > 0) {
            List<OrderRefund> list = orderRefundMapper.listOrderRefundsByParams(params, new RowBounds(offset, limit));
            for (OrderRefund or : list) {
                or.setOrder(orderMapper.selectByPrimaryKey(or.getOid()));

                OrderProductExample ope = new OrderProductExample();
                OrderProductExample.Criteria criteria = ope.createCriteria();
                criteria.andOrderidEqualTo(or.getOid())
                        .andStatusEqualTo(OrderStatus.wait_refund.getCode());
                if (or.getOgid() != null && or.getOgid() > 0) {
                    criteria.andProductIdEqualTo(or.getOgid());
                }
                or.setOrderProducts(orderProductMapper.selectByExample(ope));
            }
            pageUtils.setRows(list);
            pageUtils.setTotal(total);
        }
        return pageUtils;
    }

    @Override
    public List<OrderRefund> listOrderRefund(Date start, Date end, Long centreId, Long teamId, String queryItem, Integer status) {
        Map<String, Object> params = new HashMap<>(4);
        if (start != null) {
            params.put("start", start);
        }
        if (end != null) {
            params.put("end", end);
        }
        if (centreId != null) {
            params.put("centreId", centreId);
        }
        if (teamId != null) {
            params.put("teamId", teamId);
        }
        if (StringUtils.isNotEmpty(queryItem)) {
            params.put("queryItem", queryItem);
        }
        if (status != null) {
            params.put("status", status);
        }
        List<OrderRefund> list = orderRefundMapper.listOrderRefundsByParams(params);
        if (CollectionUtils.isNotEmpty(list)) {
            for (OrderRefund or : list) {
                or.setOrder(orderMapper.selectByPrimaryKey(or.getOid()));
            }
        }
        return list;
    }

    @Override
    public int updateRefund(OrderRefund refund) {
        if (refund == null || refund.getId() == null) {
            return 0;
        }
        return orderRefundMapper.updateByPrimaryKeySelective(refund);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int closeRefund(Long refundId, Long aid, String aname) {
        OrderRefund refund = orderRefundMapper.selectByPrimaryKey(refundId);
        if (refund == null) {
            return 0;
        }

        OrderProduct op = new OrderProduct();
        op.setStatus(OrderStatus.wait_send.getCode());
        if (refund.getOgid() != null && refund.getOgid() > 0) {
            OrderProductExample ope = new OrderProductExample();
            OrderProductExample.Criteria criteria = ope.createCriteria();
            criteria.andOrderidEqualTo(refund.getOid());
            criteria.andProductIdEqualTo(refund.getOgid());
            orderProductMapper.updateByExampleSelective(op, ope);

        } else {
            Order order = new Order();
            order.setId(refund.getOid());
            order.setStatus(OrderStatus.wait_send.getCode());
            orderMapper.updateByPrimaryKeySelective(order);

            OrderProductExample ope = new OrderProductExample();
            ope.or().andOrderidEqualTo(refund.getOid());
            orderProductMapper.updateByExampleSelective(op, ope);
        }
        refund.setCheckmid(aid.intValue());
        refund.setCheckname(aname);
        refund.setStatus(RefundStatus.refused.getCode());
        refund.setCheckTime(new Date());
        return orderRefundMapper.updateByPrimaryKeySelective(refund);
    }

//    @Override
//    public int confirmRefund(Long refundId, Long aid, String aName) {
//        OrderRefund or = orderRefundMapper.selectByPrimaryKey(refundId);
//        if (or == null) {
//            return 0;
//        }
//        or.setRefundTime(new Date());
//        or.setRefundmid(aid.intValue());
//        or.setRefundname(aName);
//        Order order = orderMapper.selectByPrimaryKey(or.getOid());
//        //只要取消订单就退还所有积分
//        //integralService.returnIntegralNew(order, order.getDeductcredit());
//        if (order.getPayIntegral().compareTo(BigDecimal.ZERO)>0) {
//            //退还积分
//            integralService.obtainIntegral(order.getMid(), order.getPayIntegral().doubleValue(), order.getId(), order.getOrdersn());
//        }
//        //只要取消订单就将相关分佣置为无效
//        commissionService.updateCommissionByOrderId(or.getOid());
//        if (PayType.WX_PAY.equals(or.getRefundtype()) || PayType.WX_APP_PAY.equals(or.getRefundtype())) {
//            //获取一条可用支付通道
//            PayChannel payChannel = payChannelService.getFirstChannel(order.getCentreId());
//            if (StringUtil.isNotEmpty(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.TFB.getCode())) {
//                //天付宝暂时退余额
//                return payService.wxTFBRefund(refundId, aid, aName);
//            } else if (StringUtils.isNotEmpty(order.getChanelcode()) && order.getChanelcode().equals(PayChannelEnum.SXF.getCode())) {
//                //随行付暂时退余额
//                return payService.wxSXFRefund(refundId, aid, aName);
//            }else if (StringUtils.isNotEmpty(order.getChanelcode()) && order.getChanelcode().equals(PayChannelEnum.JUHE.getCode())) {
//                return payService.wxJUHERefund(refundId, aid, aName);
//            }  else {
//                //微信公众号转账
//                return payService.wxRefund(refundId, aid, aName);
//            }
//
//        } else if (PayType.BALANCE_PAY.equals(or.getRefundtype())) {
//            return payService.balanceRefund(refundId, aid, aName);
//        } else {
//
//        }
//        return 0;
//    }
}
